﻿
namespace ZquenceStudio3Host.DspPlugins.Synthesizers.Nodesizer.Engine.Modules.HighLevel
{
    [ModuleDisplay("Mix")]
    class MixModule : BaseModule
    {
        public readonly ModuleInput Input1;
        public readonly ModuleInput Input2;
        public readonly ModuleOutput Out;
        public InputModuleParameter Mix { get; private set; }

        public MixModule(ModuleManager manager)
            : base(manager)
        {
            // Add input and outputs to module.
            AddInput(Input1 = new ModuleInput("In1", IOType.AudioOrWaveform, this));
            AddInput(Input2 = new ModuleInput("In2", IOType.AudioOrWaveform, this));
            AddOutput(Out = new ModuleOutput("Out", IOType.AudioOrWaveform, this));

            Mix = new InputModuleParameter(this, "Mix", 0.5, IOType.AudioOrWaveform);
            Mix.Label = "Mix";
            Mix.MinValue = 0;
            Mix.MaxValue = 1;
            AddModuleParameter(Mix);
        }

        public override void Process()
        {
            // First check if both inputs sources is connected.
            if (Input1.IsConnected && Input2.IsConnected)
            {
                for (int i = 0; i < Out.AudioBuffer.Length; i++)
                {
                    Out.AudioBuffer[i] = Input1.FromOutput.AudioBuffer[i] *(1-Mix[i]) + Input2.FromOutput.AudioBuffer[i] * Mix[i];
                }
            }
            else if (Input1.IsConnected)
            {
                for (int i = 0; i < Out.AudioBuffer.Length; i++)
                {
                    Out.AudioBuffer[i] = Input1.FromOutput.AudioBuffer[i] * (1 - Mix[i]);
                }
            }
            else if (Input2.IsConnected)
            {
                for (int i = 0; i < Out.AudioBuffer.Length; i++)
                {
                    Out.AudioBuffer[i] = Input2.FromOutput.AudioBuffer[i] * Mix[i];
                }
            }
        }
    }
}
